package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.common.consts.RabbitConst;
import com.atguigu.gmall.common.util.JsonUtil;
import com.atguigu.gmall.order.biz.OrderService;
import com.atguigu.gmall.rabbit.component.RabbitService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * @Author:lyd
 **/
@Service
public class OrderPayedListener {
    @Autowired
    RabbitService rabbitService;
    @Autowired
    OrderService orderService;

    @RabbitListener(queues = RabbitConst.QUEUE_ORDER_PAYED)
    public void handle(Message message, Channel channel) throws IOException {
        String msgStr = new String(message.getBody());
        Map<String, String> msg = JsonUtil.strToObj(msgStr, new TypeReference<Map<String, String>>() {
        });
        try {
            //执行业务，修改订单状态
            orderService.orderStatusToPayed(msg);
            //手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            rabbitService.retry(message, channel, 5);
        }
    }
}
